package com.jcake.vimlike.internal.commands;

import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Region;

import com.jcake.vimlike.RegisterManager;
import com.jcake.vimlike.internal.CommandParser;
import com.jcake.vimlike.internal.registers.Register;

public class DeleteCommand extends AbstractRegisterCountCommand {

	private String[] fullCommands = { "dd", "D", "dap", "das", "daw", "d$", "d^" };

	@Override
	protected String[] getFullCommands() {
		return fullCommands;
	}

	public void execute(String command) throws Exception {
		CommandParser parser = new CommandParser(command);
		Integer count = ((parser.getCount() != null) ? parser.getCount() : 1);
		Character register = parser.getRegister();
		String cmd = parser.getCommand();
		IDocument document = getDocument();

		Region regionForAction = new Region(-1, -1);
		Register.Type type = Register.Type.LINE_ORIENTED;

		int offset = getSelection().getOffset();
		if (cmd.equals("dd")) {
			// yank lines
			regionForAction = findLines(getDocument(), offset, count);
		} else if (cmd.equals("daw")) {
			// yank words
			regionForAction = findWords(getDocument(), offset, count);
			type = Register.Type.RANGE_ORIENTED;
		} else if (cmd.equals("das")) {
			// yank sentences
			regionForAction = findSentences(getDocument(), offset, count);
			type = Register.Type.RANGE_ORIENTED;
		} else if (cmd.equals("dap")) {
			// yank paragraphs
			regionForAction = findParagraphs(getDocument(), offset, count);
			//type = Register.Type.RANGE_ORIENTED;
		} else if (cmd.equals("d$") || cmd.equals("D")) {
			regionForAction = findRegionToEndOfLine(getDocument(), offset, count);
		} else if (cmd.equals("d^")) {
			regionForAction = findRegionFromBeginingOfLinesBackToOffset(getDocument(), offset, count);
		}

		if (regionForAction.getOffset()  < 0 || regionForAction.getLength() < 0) {
			notice("Nothing deleted!");
			return;
		}

		String extractedText = document.get(regionForAction.getOffset(), regionForAction.getLength());

		document.replace(regionForAction.getOffset(), regionForAction.getLength(), "");

		if (register != null && register.charValue() == RegisterManager.BLACK_HOLE_REGISTER) {
			return;
		}
		RegisterManager.getInstance().updateRegister(RegisterManager.UNNAMED_REGISTER, extractedText, type);
		if (register != null && Character.isDigit(register)) {
			RegisterManager.getInstance().updateRegister(register, extractedText, type);
		} else {
			RegisterManager.getInstance().updateRegister(register, extractedText, type);
			RegisterManager.getInstance().cycleNumericRegisters(extractedText, type);
		}

	}

}
